/**
Zeke Elder - zbe@andrew.cmu.edu
Amal Chemmany - achemman@andrew.cmu.edu
Nishant Kumar - nkumar1@andrew.cmu.edu
15-637
4/2/2012
 **/

package edu.cmu.fithub.actions;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.mybeans.form.FormBeanFactory;

import edu.cmu.fithub.controller.Action;
import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.Friend;
import edu.cmu.fithub.db.bean.User;
import edu.cmu.fithub.formbeans.LoginForm;

public class DeleteFriendAction extends Action {

	private FormBeanFactory<LoginForm> formFactory = FormBeanFactory
			.getInstance(LoginForm.class);

	public DeleteFriendAction() {
	}

	public String getName() {
		return "deleteFriend.do";
	}

	public String perform(HttpServletRequest request) {
		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);
		try {
			User user = (User) request.getSession().getAttribute("user");
			String id = request.getParameter("id");
			Session dbSession = DBHelper.getSessionFactory().openSession();
			Friend friend = new Friend();
			friend.setUserId(user.getUserId());
			friend.setFriendId(Integer.parseInt(id));
			List<Friend> list = dbSession.createCriteria(Friend.class)
					.add(Restrictions.eq("userId", friend.getUserId()))
					.add(Restrictions.eq("friendId", friend.getFriendId()))
					.list();
			if (list.size() != 0) {
				friend = list.get(0);
				dbSession.beginTransaction();
				dbSession.delete(friend);
				dbSession.getTransaction().commit();
			} else {
				errors.add("Error: No such friend exists!!");
				return "error.jsp";
			}

			return "displayFriends.do";

		} catch (NumberFormatException e) {
			errors.add(e.getMessage());
			return "error.jsp";
		}
	}
}
